import { ref, onMounted, onBeforeUnmount, type Ref } from 'vue'

export function useContextMenu(container: Ref<HTMLElement>) {
  const visiable = ref(false)
  const x = ref(0)
  const y = ref(0)
  const contextMenuHandler = (e: MouseEvent) => {
    e.preventDefault()
    x.value = e.clientX
    y.value = e.clientY
    visiable.value = true
  }
  const closehandler = () => {
    visiable.value = false
  }
  onMounted(() => {
    container.value.addEventListener('contextmenu', contextMenuHandler)
    window.addEventListener('click', closehandler)
    window.addEventListener('scroll', closehandler)
  })
  onBeforeUnmount(() => {
    container.value.removeEventListener('contextmenu', contextMenuHandler)
    window.removeEventListener('click', closehandler)
    window.removeEventListener('scroll', closehandler)
  })
  return {
    x,
    y,
    visiable,
  }
}
